package com.sunmi.usercenter.ui.activity.fragment;

import java.lang.reflect.Type;
import org.apache.http.Header;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sunmi.usercenter.Constant;
import com.sunmi.usercenter.R;
import com.sunmi.usercenter.bean.FmInfo;
import com.sunmi.usercenter.bean.Result;
import com.sunmi.usercenter.bean.VerificationcodeBean;
import com.sunmi.usercenter.bean.rpc.ReqGetVerificationCode;
import com.sunmi.usercenter.bean.rpc.ReqVerifyCode;
import com.sunmi.usercenter.ui.component.LoadingDialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 项目名称：Sunmi-User-Center 类描述：输入验证码的界面 创建人：Abtswiath丶lxy 创建时间：2016/6/7 11:37
 * 修改人：longx 修改时间：2016/6/7 11:37 修改备注：
 */
public class InputCodeFragment extends SuperFragment implements OnClickListener ,TextWatcher{

	private View mView;
	private TextView mTxtTitle, mTxtInfo, mTxtSendCode, mTxtCodeError;
	private EditText mEdtxtCode;
	private RelativeLayout mRelBack,mRelClear;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView();
		initData();
	}

	/**
	 * 初始化UI数据
	 */
	private void initData() {
		
		if (Constant.mInputToCode.getSelectMode().equals(RegisterFragment.EMAIL)) {
			mTxtTitle.setText(getString(R.string.input_email_verification_code));
			mTxtInfo.setText(getString(R.string.to_your_email) + Constant.mInputToCode.getUsername()
					+ getString(R.string.send_one_email));
		} else {
			mTxtTitle.setText(getString(R.string.input_SMS_verification_code));
			mTxtInfo.setText(getString(R.string.to_your_phone) + "+86" + Constant.mInputToCode.getUsername()
					+ getString(R.string.send_one_SMS_verification_code));
		}
		mTxtSendCode.setText(getString(R.string.try_send));
		mTxtCodeError.setVisibility(View.INVISIBLE);
	}
	
	

	/**
	 * 初始化
	 */
	private void initView() {
		mActivity.SetStatusColorf5f5f5();
		mRelBack = (RelativeLayout) mView.findViewById(R.id.back);
		mTxtTitle = (TextView) mView.findViewById(R.id.title);
		layoutTitle(mTxtTitle);
		mTxtInfo = (TextView) mView.findViewById(R.id.txt_info);
		mTxtSendCode = (TextView) mView.findViewById(R.id.txt_try_send);
		TextView mBtnNext = (TextView) mView.findViewById(R.id.btn_next);
		mEdtxtCode = (EditText) mView.findViewById(R.id.txt_password);
		mTxtCodeError = (TextView) mView.findViewById(R.id.txt_error);
		mRelBack.setOnClickListener(this);
		mTxtSendCode.setOnClickListener(this);
		mBtnNext.setOnClickListener(this);
		mRelClear = (RelativeLayout) mView.findViewById(R.id.rel_clear);
		mRelClear.setVisibility(View.GONE);
		mRelClear.setOnClickListener(this);
		mEdtxtCode.addTextChangedListener(this);
		time = new TimeCount(60000,1000);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		return mView = inflater.inflate(R.layout.fragment_input_code, container, false);
	}
	
	/**
	 * 点击重新发送
	 */
	private void sendCode() {
		changeSendBtnCode();
		ReqGetVerificationCode reqGetVerificationCode = new ReqGetVerificationCode();
		reqGetVerificationCode.setUserName(Constant.mInputToCode.getUsername());
		if(!getActivity().getResources().getConfiguration().locale.getCountry().equals("CN")){
			reqGetVerificationCode.setLanguage(1);
		}
		mHttpController.getVerificationCode(reqGetVerificationCode, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int i, Header[] headers, byte[] bytes) {
				analysis(bytes);
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				showToast(getString(R.string.req_error));
			}
		});
	}
	
	
	private void sendCodeRetrieve() {
		changeSendBtnCode();
		ReqGetVerificationCode reqGetVerificationCode = new ReqGetVerificationCode();
		reqGetVerificationCode.setUserName(Constant.mInputToCode.getUsername());
		if(!getActivity().getResources().getConfiguration().locale.getCountry().equals("CN")){
			reqGetVerificationCode.setLanguage(1);
		}
		mHttpController.getVerificationCode4Retrieve(reqGetVerificationCode, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int i, Header[] headers, byte[] bytes) {
				analysis(bytes);
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				showToast(getString(R.string.req_error));
			}
		});
	}
	
	private void analysis(byte[] bytes){
		String json = new String(bytes);
		Gson gson = new Gson();
		Type type = new TypeToken<Result<VerificationcodeBean>>() {
		}.getType();
		Result<VerificationcodeBean> result = null;
		try {
			result = gson.fromJson(json, type);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (result != null) {
			if (result.code == 1) {
				showToast(getString(R.string.get_code_success));
			}else if(result.code==160038){
				showToast(getString(R.string.code_send_failed));
			}else if(result.code==160042){
				showToast(getString(R.string.the_address_error_to_phone));
			}else if(result.code==160039||result.code==160040||result.code==160041){
				showToast(getString(R.string.phone_get_code_max_error));
			}else{
				showToast(getString(R.string.code_send_failed));
			}
		} else {
			showToast(getString(R.string.code_send_failed));
		}
	}

//	private Timer mTimer;
//	private TimerTask mTimerTask;
//	private int mDelay = 60;

	class TimeCount extends CountDownTimer{
		public TimeCount(long millisInFuture, long countDownInterval){
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			mTxtSendCode.setText(millisUntilFinished/1000 + "S");
			mTxtSendCode.setEnabled(false);
		}

		@Override
		public void onFinish() {
			mTxtSendCode.setText(getString(R.string.try_send));
			mTxtSendCode.setEnabled(true);
		}
	}


	private TimeCount time;
	private void changeSendBtnCode() {




		time.start();
//┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃ 　
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//┃　　　┃  神兽保佑　　　　　　　　
//┃　　　┃  代码无BUG！
//┃　　　┗━━━┓
//┃　　　　　　　┣┓
//┃　　　　　　　┏┛
//┗┓┓┏━┳┓┏┛
// ┃┫┫　┃┫┫
// ┗┻┛　┗┻┛

	}


	
	private LoadingDialog mLoadingDialog;
	/**
	 * 点击下一步
	 */
	private void next() {
		final String code = mEdtxtCode.getText().toString().trim();
		if (code == null) {
			showToast(getString(R.string.please_input_verification_code));
			return;
		} else {
			mLoadingDialog = LoadingDialog.createDialog(getActivity(), getString(R.string.waitting));
			mLoadingDialog.show();
			ReqVerifyCode reqVerifyCode = new ReqVerifyCode();
			reqVerifyCode.setCode(code);
			reqVerifyCode.setUserName(Constant.mInputToCode.getUsername());
		mHttpController.verifyCode(reqVerifyCode, new AsyncHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String json = new String(arg2);
				Gson gson = new Gson();
				@SuppressWarnings("rawtypes")
				Result result = null;
				try {
					result = gson.fromJson(json, Result.class);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(result!=null&&result.code==1){
					Constant.mInputToCode.setCode(code);
					openFM(new FmInfo(SettingPsdFragment.class, null));
				}else{
					mTxtCodeError.setVisibility(View.VISIBLE);
				}
				mLoadingDialog.dismiss();
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				showToast(getString(R.string.please_try));
				mLoadingDialog.dismiss();
			}
		});		
		
//		if (mInputToCode.getCode() != null && mInputToCode.getCode().equals(code)) {
//			openFM(new FmInfo(SettingPsdFragment.class, mInputToCode));
//		} else {
//			mTxtCodeError.setVisibility(View.VISIBLE);
//		}
	}
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			onBack();
			break;
		case R.id.txt_try_send:
			if(Constant.mInputToCode.getFramgment()==1){
				sendCode();
			}else{
				sendCodeRetrieve();
			}
			break;
		case R.id.btn_next:
			next();
			break;
		case R.id.rel_clear:
			mEdtxtCode.setText("");
			break;
		default:
			break;
		}
	}
	
	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if(time!=null){
			time.cancel();
			time = null;
		}
	}
	


	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	@Override
	public void afterTextChanged(Editable s) {
		if(s.length()>0){
			mRelClear.setVisibility(View.VISIBLE);
		}else{
			mRelClear.setVisibility(View.GONE);
		}
	}
}
